package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;

import com.conversationboard.batch.scheduler.Jobs;
import com.conversationboard.config.Configuration;
import com.conversationboard.logger.LogMessageType;
import com.conversationboard.logger.Logger;
import com.conversationboard.model.User;

@WebServlet(name = "AdminBatchJobToggleControllerServlet", urlPatterns = "/Admin/AdminBatchJobToggleControllerServlet")
public class AdminBatchJobToggleControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -4443626693432164060L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {
			User user = User.get(request.getUserPrincipal().getName());

			if ((!user.isSiteAdmin()) || (!SecurityChecks.passes(request, user, this))) {
				return;
			}

			Scheduler scheduler = Jobs.getScheduler();

			if (scheduler.isInStandbyMode()) {
				scheduler.start();
				Logger.log(new Date(), "Batch scheduler started.", user, LogMessageType.SYSTEM);
			} else {
				scheduler.standby();
				Logger.log(new Date(), "Batch scheduler stopped.", user, LogMessageType.SYSTEM);
			}

			response.sendRedirect(Configuration.getInstance().getRoot() + "/Admin/AdminBatchJobStatusControllerServlet");

		} catch (SchedulerException e) {
			throw new ServletException(e);
		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
